<template>
  <div class="app-container">
    <div class="app-container-table-border">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="标准清单1" prop="sheetTypeName">
          <el-input v-model="queryParams.sheetTypeName" placeholder="请输入标准清单" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-form ref="tableForm" :model="form" :rules="rules" label-width="0px">
        <el-table border stripe v-loading="loading" :data="dataList" :span-method="objectSpanMethod"
          :summary-method="getSummaries" show-summary>
          <el-table-column label="序号" align="center" property="vuhao" width="50" />
          <el-table-column label="清单名称" header-align="center" property="sheetTypeName" min-width="140"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.sheetTypeName || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号名称" header-align="center" property="sheetFeaturesName" min-width="120"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.sheetFeaturesName || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" property="sheetUnit" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.sheetUnit || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" property="initDanjia" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.initDanjia || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" header-align="center" align="right" property="initRongliang" width="120">
            <template slot-scope="scope">
              <el-form-item v-if="canUpdate && scope.row.sheetId" :prop="'dataList.' + scope.$index + '.initRongliang'"
                :rules="rules.initRongliang">
                <el-input-number size="mini" v-model="scope.row.initRongliang" placeholder="" :precision="2"
                  :controls="false" style="width: 100%;" @change="computeInitZongjia(scope.row)"></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.initRongliang || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="变更数量" header-align="center" align="right" property="chgRongliang" width="120">
            <template slot-scope="scope">
              <el-form-item v-if="canAlteration && scope.row.sheetId"
                :prop="'dataList.' + scope.$index + '.chgRongliang'" :rules="rules.chgRongliang">
                <el-input-number size="mini" v-model="scope.row.chgRongliang" placeholder="" :precision="2"
                  :controls="false" style="width: 100%;" @change="computeEditZongjia(scope.row)"></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.chgRongliang || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="价税合计" header-align="center" align="right" property="initZongjia" width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.initZongjia || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="变更后合计" header-align="center" align="right" property="chgZongjia" width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.chgZongjia || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="税率(%)" header-align="center" align="right" property="sheetTaxRate" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.sheetTaxRate || "-" }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
  </div>
</template>

<script>
import { listDataBzqd, listBaContractSheets, getBaContractSheets, delBaContractSheets, addBaContractSheets, updateBaContractSheets, editBatchBaContractSheets } from "@/api/cm/baContractSheets";
import { mapGetters } from "vuex";
import decimal from "@/utils/big-decimal";

export default {
  name: "BaContractSheets",
  dicts: ['report_status'],
  components: {
  },
  props: {
    bdId: {
      type: [String, Number],
      default: ''
    },
    zdId: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同清单详情表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractId: undefined,
        bdId: undefined,
        zdId: undefined,
        standardId: undefined,
        initZongjia: undefined,
        initRongliang: undefined,
        initDanjia: undefined,
        initShui: undefined,
        ljbgZongjia: undefined,
        ljbgRongliang: undefined,
        ljbgDanjia: undefined
      },
      // 表单参数
      form: {
        bolist: []
      },
      editForm: {},
      // 表单校验
      rules: {
        // initRongliang: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        // initDanjia: [{ required: true, message: "单价不能为空", trigger: "blur" }]
      },
      tableBzqdData: [],
      multipleSelection: [],
      editOpen: false,
      dayTableTotal: {},
      reportStatus: '00',
      //合并表格
      columnArr: ["vuhao", "sheetTypeName", "sheetFeaturesName"],
      spanData: [],
      canUpdate: false, // 编辑
      canAlteration: false, // 变更
    };
  },
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    bdId: {
      deep: true,
      immediate: true,
      handler (val) {
        this.queryParams.bdId = val;
        this.queryParams.zdId = this.zdId;
        this.getList();
      }
    }
  },
  created () {
  },
  methods: {

    /** 查询合同清单详情列表 */
    getList () {
      this.loading = true;
      listBaContractSheets(this.queryParams).then((response) => {
        this.dataList = response.cmBaContractSheetsVos || [];
        this.reportStatus = '00';
        if (this.dataList.length > 0) {
          this.reportStatus = this.dataList[0].approvalStatus;
          this.ids = this.dataList.map((item) => item.standardId);
          this.getSpanData(this.dataList);
        } else {
          this.ids = [];
        }
        // this. = response.cmBaContractSheetsVos;
        this.dayTableTotal = response.total || {}; //总计
        this.loading = false;
        this.canUpdate = false;
        this.$forceUpdate();
      });
    },
    // 拼接合计
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        // sums[1] = "-";
        // sums[2] = "-";
        // sums[3] = "-";
        // sums[5] = this.dayTableTotal?.rongliangTotal || "-";
        // // sums[5] = "-";
        // sums[6] = this.dayTableTotal?.zongjiaTotal || "-";
        // sums[7] = "-";
        // sums[8] = "-";
        if (index >= 5 && index <= 8) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return decimal.add(prev, curr);
              } else {
                return decimal.round(prev);
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    },

    // 计算需要合并的单元格
    getSpanData (data) {
      if (!data || data.length === 0 || !this.columnArr || this.columnArr.length === 0) {
        return;
      }
      this.spanData = [];
      for (let i = 0; i < this.columnArr.length; i++) {
        let contactDot = 0;
        const spanArr = [];
        data.forEach((item, index) => {
          // console.log(item)
          if (index === 0) {
            spanArr.push(1);
          } else {
            const isMergeRow = this.isMerge(data[index - 1], item, i);
            if (isMergeRow) {
              spanArr[contactDot] += 1;
              spanArr.push(0);
            } else {
              contactDot = index;
              spanArr.push(1);
            }
          }
        });
        this.spanData.push(spanArr);
      }

      // console.log(this.spanData)
    },
    // 是否合并
    isMerge (prevItem, item, index) {
      let ret = true;
      for (let i = 0; i <= index; i++) {
        const element = this.columnArr[i];
        if (item[element] !== prevItem[element]) {
          ret = false;
          break;
        }
      }
      return ret;
    },
    // 合并单元格
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (this.columnArr.includes(column.property)) {
        const index = this.columnArr.findIndex((item) => {
          return item == column.property;
        });
        if (this.spanData[index]) {
          if (this.spanData[index][rowIndex]) {
            return {
              rowspan: this.spanData[index][rowIndex],
              colspan: 1,
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            };
          }
        }
      }
    },

    editOpenCancel () {
      this.loading = false;
      this.editOpen = false;
      this.editReset();
    },
    // 表单重置
    editReset () {
      this.editForm = {
        contractId: undefined,
        bdId: undefined,
        zdId: undefined,
        sheetId: undefined,
        standardId: undefined,
        initZongjia: undefined,
        initRongliang: undefined,
        initDanjia: undefined,
        initShui: undefined,
        ljbgZongjia: undefined,
        ljbgRongliang: undefined,
        ljbgDanjia: undefined,
        ljbgShui: undefined,
        factZongjia: undefined,
        factRongliang: undefined,
        factDanjia: undefined,
        factShui: undefined,
        factWcrl: undefined,
        factWczj: undefined,
        factZfyfk: undefined,
        factKcyfk: undefined,
        factKk: undefined,
        factFkbl: undefined,
        factFk: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd () {
      if (!this.treeInfo?.parentId) {
        this.$modal.msgError(`请先在左侧选择合同所属站点！`);
        return;
      }
      this.editReset();
      this.$refs.sheetAddRef.init();
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      // this.loading = true;
      this.editReset();
      this.editForm = JSON.parse(JSON.stringify(row));
      this.editOpen = true;
    },
    // 批量修改
    onEditBatch () {
      this.canUpdate = true;
    },
    // 批量修改提交
    doEditBatch () {
      this.buttonLoading = true;
      editBatchBaContractSheets(this.dataList)
        .then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        })
        .finally(() => {
          this.buttonLoading = false;
          this.canUpdate = false;
        });
    },
    // 修改提交
    editFormSet () {
      this.buttonLoading = true;
      updateBaContractSheets(this.editForm)
        .then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.editOpen = false;
          this.getList();
        })
        .finally(() => {
          this.buttonLoading = false;
        });
    },

    /** 删除按钮操作 */
    handleDelete (row) {
      const sheetIds = row.sheetId || this.ids;
      this.$modal
        .confirm('是否确认删除清单类别名称为"' + row.sheetTypeName + "规格型号名称为" + (row.sheetFeaturesName || '-') + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delBaContractSheets(sheetIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },
    // 计算总价
    countEditJshj () {
      let a = this.editForm.initRongliang; //数量
      let b = this.editForm.initDanjia; //单价
      this.editForm.initZongjia = decimal.multiply(a, b);
    },
    // 计算总价
    computeInitZongjia (row) {
      let a = row.initRongliang; //数量
      let b = row.initDanjia; //单价
      row.initZongjia = decimal.multiply(a, b);
    },
    /** 发起审批 */
    onExamine () {
      const projectInfo = this.sysProjectList.find(item => item.projectId == this.sysProjectId);
      const info = {
        projectId: this.sysProjectId,
        projectName: projectInfo.projectName,
        bdId: this.queryParams.bdId
      };
      this.$refs.examineAndApproveRef.init(info);
    },
    // 是否可操作
    canOperation () {
      return this.reportStatus == '00' || this.reportStatus == '33';
    },
    // 状态字典翻译
    reportStatusFormat () {
      return this.selectDictLabel(this.dict.type.report_status, this.reportStatus);
    },
  }
};
</script>
